<?php

namespace app\index\model;

use app\model\Model;

class Channel extends Model
{
  public $title, $keywords, $description;
  public $c_main;
  public $db;

  function __construct()
  {
    $this->db = $GLOBALS['db'];
  }

  function index()
  {
    $id = intval($_GET['id']);
    non_numeric_href($id, $GLOBALS['lang']['illegal'], './');

    include_once LIB_PATH . 'cls.channel.php';
    $objChannel = new \Channel();
    $channel = $objChannel->getChannel($id);

    if (empty($channel)) {
      alert_href($GLOBALS['lang']['illegal'], './');
    }
    $channel = stripslashes_deep($channel);
    // set_url_back();

    $this->title = $channel['c_name'] . '-' . $GLOBALS['cms']['name'];
    $this->keywords = !empty($channel['c_keywords']) ? $channel['c_keywords'] : $channel['c_name'];
    $this->description = !empty($channel['c_description']) ? $str_cut(str_text($channel['c_description'], 1), 220) : str_cut(str_text($GLOBALS['cms']['description'], 1), 220);

    $this->c_main = $channel['c_main'];
    // 获取相关信息
    $channel['c_sub'] = $channel['c_ifsub'] ? $channel['c_sub'] : $channel['id'];
    $channel_slist = channel_slist($channel['c_ifsub'] == 1 ? $channel['id'] : $channel['c_parent'], $channel['id']);
    $current_channel_location = current_channel_location($channel['id'], $channel['id']);

    // 获取上级信息
    $channel_parent = $objChannel->getParent($channel['id']);
    $channel_main = $objChannel->getMain($channel['id']);

    // 获取子集列表
    $channel_sub = $objChannel->getSon($channel['id']);

    // 分页&列表
    if (strpos($channel['c_cmodel'], 'list')) {
      include LIB_PATH . 'cls.page.php';
      $pager = new \Page($channel['c_page']);
      if (!empty($channel['c_sub'])) {
        $pager->handle($GLOBALS['db']->getOne("SELECT COUNT(id) FROM detail WHERE d_parent IN (" . $channel['c_sub'] . ")"));
        $list_pager = $GLOBALS['db']->getAll("SELECT id,d_name,d_picture,d_link,d_order FROM detail WHERE d_parent IN (" . $channel['c_sub'] . ") ORDER BY d_order ASC,id DESC LIMIT " . $pager->page_start . "," . $pager->page_size);
      } else {
        $pager->handle($GLOBALS['db']->getOne("SELECT COUNT(id) FROM detail WHERE d_parent = " . $channel['id']));
        $list_pager = $GLOBALS['db']->getAll("SELECT id,d_name,d_picture,d_link,d_order FROM detail WHERE d_parent = " . $channel['id'] . " ORDER BY d_order ASC,id DESC LIMIT " . $pager->page_start . "," . $pager->page_size);
      }
    }

    $this->tpl($channel['c_cmodel'], [
      'db' => $this->db,
      'channel' => $channel,
      'channel_slist' => $channel_slist,
      'current_channel_location' => $current_channel_location,
      'channel_parent' => $channel_parent,
      'channel_main' => $channel_main,
      'channel_sub' => $channel_sub,
      'pager' => $pager,
      'list_pager' => $list_pager,
    ]);
  }

  function __destruct()
  {
  }
}